package com.tqz.rc.spring.cloud.registry;

import org.springframework.cloud.client.serviceregistry.AbstractAutoServiceRegistration;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationProperties;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.cloud.client.serviceregistry.ServiceRegistry;
import org.springframework.context.ApplicationListener;

/**
 * <p>构造方法会调用父类的构造方法，而父类 {@link AbstractAutoServiceRegistration} 实现了 {@link ApplicationListener} 接口，
 *  会执行 onApplicationEvent()--->bind()--->start()--->进入到本类的register()方法，
 *  然后调用父类的register()方法--->TqzRcServiceRegistry#register()，实现服务的注册功能。
 *
 * @author tianqingzhao
 * @since 2021/9/2 15:45
 */
public class TqzRcAutoServiceRegistration extends AbstractAutoServiceRegistration<Registration> {

    private TqzRcRegistration registration;

    protected TqzRcAutoServiceRegistration(ServiceRegistry<Registration> serviceRegistry,
                                           AutoServiceRegistrationProperties autoServiceRegistrationProperties,
                                           TqzRcRegistration registration) {

        super(serviceRegistry, autoServiceRegistrationProperties);
        this.registration = registration;
    }

    @Override
    protected Object getConfiguration() {
        return this.registration.getTqzRcProperties();
    }

    @Override
    protected boolean isEnabled() {
        return true;
    }

    @Override
    protected Registration getRegistration() {
        if (this.registration.getPort() <= 0 && this.getPort().get() > 0 ) {
            this.registration.setPort(getPort().get());
        }
        return registration;
    }

    @Override
    protected Registration getManagementRegistration() {
        return null;
    }

    @Override
    protected void register() {
        if (!this.registration.getTqzRcProperties().isRegisterEnable()) {
            return;
        }

        super.register();
    }
}
